package com.xudow.app.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.Toast;

import com.activeshare.edu.ucenter.common.messages.user.UserDetailMessage;
import com.activeshare.edu.ucenter.models.user.UserProfileWithOther;
import com.jude.utils.JUtils;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.Version;
import com.xudow.app.XApplication;
import com.xudow.app.dynamicstate_old.module.guide.ClazzActivity;
import com.xudow.app.dynamicstate_old.module.guide.RoleActivity;
import com.xudow.app.model.SimpleUser;
import com.xudow.app.newui.home.HomeActivity;
import com.xudow.app.ui.task.LoginTask;
import com.xudow.app.ui.task.UserProfileTask;
import com.xudow.app.util.Maps;
import com.xudow.app.util.NetworkUtils;
import com.xudow.app.util.PrefUtils;
import com.xudow.app.util.StringUtils;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 启动界面 张良平 测试班级
 */

public class SplashActivity extends Activity {

    private LoginTask loginTask;
    private UserProfileTask userProfileTask;
    private SimpleUser user;
    private Timer timer;
    private boolean toSeletGrade=false;
   // private boolean iscomplate=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        timer=new Timer();
        TimerTask timerTask=new TimerTask() {
            @Override
            public void run() {

                    tryLoginHandler.sendEmptyMessage(1);
                timer.cancel();
            }
        };
        timer.schedule(timerTask,2000);
        PushAgent.getInstance(this).onAppStart();
        if (NetworkUtils.isNetWorkConnected(this)) {
            JUtils.Log("start Login");
            //是否有保存用户密码
            user = PrefUtils.getUserInfo(getApplicationContext());

            if (!user.getUsername().equals("")) {

                PushAgent.getInstance(getApplicationContext()).enable();
                login();
            } else {
                tryLoginHandler.sendEmptyMessageDelayed(0, 1000);

            }

        } else {
            Toast.makeText(this, R.string.common_network_err, Toast.LENGTH_LONG).show();
            tryLoginHandler.sendEmptyMessageDelayed(0, 1000);
        }
    }


    private Handler tryLoginHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            XApplication app=(XApplication)getApplication();
            if (!app.isHasAttentionType()){
                toSeletGrade=true;
            }
            if (msg.what==0) {
                tryLogin();
            }else if (msg.what==1){
                Intent intent;
                if (toSeletGrade){
                    intent=new Intent(SplashActivity.this, ClazzActivity.class);
                    intent.putExtra("isLogin", true);
                }else
                    intent=new Intent(SplashActivity.this, HomeActivity.class);
                startActivity(intent);
                finish();
            }

        }
    };

    private void tryLogin() {

        if (Version.PUBLIC_VERSION) {
           // startActivity(new Intent(this, HomeActivity.class));
           // finish();

        } else {
            if (PrefUtils.isLoginBefore(this)) {
                login();
            } else {
                startActivity(new Intent(this, LoginActivity.class));
                finish();
            }
        }
    }

    private void login() {
        HashMap<String, String> params = Maps.newHashMap();
        params.put("username", user.getUsername());
        params.put("password", user.getPassword());

        loginTask = new LoginTask(this, loginHandler);
        loginTask.execute(params);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (null != loginTask && !loginTask.isCancelled()) {
                loginTask.cancel(true);
                loginTask = null;
            }

            finish();

            return false;
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 登陆处理Handler
     */
    private Handler loginHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            PushAgent mPushAgent = PushAgent.getInstance(getApplicationContext());
            if (LoginTask.LOGIN_SUCCESS == msg.what) {
//                try {
//                    mPushAgent.addAlias(user.getUsername(), Config.XUDOW_UMENG_MSG_ALIAS);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                mPushAgent.enable();
                userProfileTask = new UserProfileTask(SplashActivity.this, userprofileHandler);
                userProfileTask.execute();
            } else {
                mPushAgent.disable();
                Toast.makeText(SplashActivity.this, "自动登录失败", Toast.LENGTH_SHORT).show();
               // startActivity(new Intent(SplashActivity.this, HomeActivity.class));
               // finish();
            }
        }
    };

    /**
     * 用户基本信息Handler
     */
    private Handler userprofileHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (UserProfileTask.SUCCESS == msg.what) {
                Bundle data = msg.getData();
                UserDetailMessage ud = (UserDetailMessage) data.getSerializable("profile");
                UserProfileWithOther profile = ud.getUserDetail();

                XApplication application = (XApplication) getApplication();
                application.setUserProfileId(profile.getId());
                application.setProfile(profile);
                //用户必须绑定手机号s
                if (StringUtils.isEmpty(profile.getMobilePhone())) {
                    startActivity(new Intent(SplashActivity.this, MobilePhoneBindActivity.class));
                } else if (!application.isHasAttentionType()) {
                    toSeletGrade=true;
                   /* Intent intent = new Intent(SplashActivity.this, ClazzActivity.class);
                    intent.putExtra("isLogin", true);
                    startActivity(intent);*/
                } else {
                    //startActivity(new Intent(SplashActivity.this, HomeActivity.class));
                }
                //finish();
            } else {
               // startActivity(new Intent(SplashActivity.this, HomeActivity.class));
                //finish();

            }
        }
    };

}
